/* eslint-disable no-param-reassign */
/* eslint-disable eqeqeq */
import React from 'react';
import router from 'umi/router';
import { connect } from 'dva';
import { UploadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Input, Select, Row, Col, Checkbox, message, DatePicker, Upload } from 'antd';
import ReactQuill from 'react-quill'; // 引入富文本编辑器
import 'react-quill/dist/quill.snow.css';
import FooterToolbar from '@/components/FooterToolbar';
import PageHeaderWrapper from '@/components/PageHeaderWrapper'; // 引入头部组件
import { requestHeadersMd5 } from '@/utils/utils';
import styles from './index.less';
import HOCSelect from '@/components/AntDesign/Select';

const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;
const { Option } = Select;
@connect(({ guideprotect }) => ({
  guideprotect,
}))
class BasicList extends React.Component {
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'guideprotect/queryDictItemsByCodes',
      payload: ['BIZ_INS_TYPE', 'BIZ_ACCU_TYPE'],
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'guideprotect/updateModelData',
      payload: {
        policyData: [],
        cityChild: [],
        affixArr: [],
        contentData: {},
        content: '',
        vno: '',
        detailId: '',
      },
    });
  }

  // 富文本编辑器 时间
  handleChange = content => {
    const { dispatch } = this.props;
    dispatch({
      type: 'guideprotect/updateModelData',
      payload: {
        content,
      },
    });
  };

  // 得到字典项中的code
  getCode = (codeArr, valueArr, valueParam) => {
    let cityCode = '';
    valueArr.forEach((value, index) => {
      if (valueParam == value) {
        cityCode = codeArr[index];
      }
    });
    return cityCode;
  };

  // 取消
  goBack = () => {
    router.push('/searchmanage/guideprotect/index');
  };

  handleSubmit = e => {
    e.preventDefault();
    const {
      form,
      dispatch,
      guideprotect: { content },
    } = this.props;
    // return
    form.validateFields((err, values) => {
      // 处理入参格式
      if (!err) {
        const tempArr = [];
        let affix = '';
        if (values.affix) {
          values.affix.forEach(value => {
            if (value.response.success) {
              tempArr.push(value.response.data);
            }
          });
          affix = tempArr.join(',');
        }
        values.type = values.type.join(',');
        values.affix = affix;
        values.content = content;
        values.publishTime = values.publishTime ? values.publishTime.valueOf() : undefined;
        values.areaName = values.areaId.label;
        values.areaId = values.areaId.key;

        dispatch({
          type: 'guideprotect/handleSubmit',
          payload: values,
        }).then(res => {
          if (res.success) {
            router.push('/searchmanage/guideprotect/index');
          } else {
            message.warning(res.message || '服务端错误');
          }
        });
      }
    });
  };

  normFile = e => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  cityChange = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'guideprotect/cityChange',
      payload: { areaName: value },
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
      guideprotect: { policyData, cityChild },
    } = this.props;
    const cityChildOpt = cityChild.map(value => (
      <Option key={value.areaId} value={value.areaId}>
        {value.areaName}
      </Option>
    ));
    const formItemLayout = {
      labelCol: { md: { span: 4 } },
      wrapperCol: { md: { span: 16 } },
    };

    const nowModules = {
      toolbar: [
        [{ header: [1, 2, 3, 4, 5, 6, false] }], // 文字大小
        ['bold', 'italic', 'underline'], // 切换组，【加粗、倾斜、下划线、删除线strike】
        //			['blockquote', 'code-block'],   // 左竖线     代码格式   二选一
        //			[{ 'header': 1 }, { 'header': 2 }],               // 标题大小
        [{ list: 'ordered' }, { list: 'bullet' }], // 列表，数字|黑点 标记
        //			[{ 'script': 'sub'}, { 'script': 'super' }],      // 右下标，右上标
        //			[{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
        //			[{ 'direction': 'rtl' }],                         // text direction
        [{ size: ['small', false, 'large', 'huge'] }], // 行距
        [{ color: [] }, { background: [] }], // 文字颜色，背景色
        [{ font: [] }], // font-family
        [{ align: [] }], // text-align
        ['clean'], // 清除所有样式
      ],
    };
    // 富文本编辑器总配置
    const quillConfig = {
      theme: 'snow',
      modules: nowModules,
      placeholder: '请输入政策内容',
    };
    const props = {
      name: 'file',
      action: '/osApi/fileServer/uploadFile',
      headers: {
        authorization: 'authorization-text',
        ...requestHeadersMd5(),
      },
      onChange(info) {
        if (info.file.status === 'done') {
          message.success(`${info.file.name} 上传成功！`);
        } else if (info.file.status === 'error') {
          message.error(`${info.file.name} 上传失败！`);
        }
      },
    };

    return (
      <PageHeaderWrapper>
        <Card title="政策新增">
          <Form>
            <FormItem {...formItemLayout} label="政策标题">
              {getFieldDecorator('tit', {
                rules: [{ required: true, message: '请输入政策标题' }],
              })(<Input placeholder="请输入供应商名称" style={{ width: 200 }} />)}
            </FormItem>
            <FormItem {...formItemLayout} label="政策类型">
              {getFieldDecorator('type', {
                rules: [{ required: true, message: '请选择政策类型' }],
              })(
                <CheckboxGroup style={{ width: '100%' }}>
                  {/* <Row> */}
                  {policyData &&
                    policyData.map(value => (
                      /* <Col span={4} key={value.itemCode}> */

                      <Checkbox value={value.itemCode}>{value.itemName}</Checkbox>
                      /* </Col> */
                    ))}
                  {/* </Row> */}
                </CheckboxGroup>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="政策地区">
              {getFieldDecorator('areaId', {
                rules: [{ required: true, message: '请输入政策地区' }],
              })(
                <HOCSelect
                  labelInValue
                  filterOption={false}
                  notFoundContent={null}
                  onSearch={this.cityChange}
                  showSearch
                  onSelect={this.citySelect}
                >
                  {cityChildOpt}
                </HOCSelect>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="来源">
              {getFieldDecorator('source', {
                rules: [{ required: false, message: '请输入来源' }],
              })(<Input placeholder="请输入来源" />)}
            </FormItem>
            <FormItem {...formItemLayout} label="公布时间">
              {getFieldDecorator('publishTime', {
                rules: [{ required: false, message: '请选择公布时间' }],
              })(<DatePicker />)}
            </FormItem>
            <FormItem {...formItemLayout} label="关键字">
              {getFieldDecorator('keyWord', {
                rules: [{ required: true, message: '请输入关键字' }],
              })(<Input placeholder="请输入关键字(多个关键字请用逗号隔开)" />)}
            </FormItem>
            <Row style={{ marginTop: 15, minHeight: '250px', marginBottom: 20 }}>
              <Col span={4} offset={0} className={styles.selfLabel} style={{ lineHeight: '32px' }}>
                <span
                  style={{
                    color: '#f5222d',
                    marginRight: 4,
                    fontFamily: 'SimSun, sans-serif',
                    fontWeight: 'normal',
                  }}
                >
                  *
                </span>
                <span style={{ color: '#262626', fontSize: '14px', fontWeight: 'normal' }}>
                  政策内容 :
                </span>
                &nbsp;&nbsp;&nbsp;
              </Col>
              <Col span={16} offset={0}>
                <ReactQuill
                  {...quillConfig}
                  onChange={this.handleChange}
                  style={{ height: '200px', overflowY: 'visible' }}
                />
              </Col>
            </Row>
            <FormItem {...formItemLayout} label="上传附件">
              {getFieldDecorator('affix', {
                valuePropName: 'fileList',
                getValueFromEvent: this.normFile,
              })(
                <Upload {...props}>
                  <Button>
                    <UploadOutlined /> 点击上传
                  </Button>
                </Upload>
              )}
            </FormItem>
          </Form>
        </Card>
        <FooterToolbar>
          <Button onClick={this.goBack} style={{ marginRight: 8 }}>
            {' 取消 '}
          </Button>
          <Button type="primary" onClick={this.handleSubmit}>
            提交
          </Button>
        </FooterToolbar>
      </PageHeaderWrapper>
    );
  }
}

const WrappedHorizontalLoginForm = Form.create()(BasicList);

export default WrappedHorizontalLoginForm;
